package br.com.ac.fatureweb.utilitary;

import java.util.Collection;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

@SuppressWarnings("all")
@FacesConverter("entityConverter")
public class EntityConverter implements Converter {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext
	 * , javax.faces.component.UIComponent, java.lang.String)
	 */
	@Override
	public Object getAsObject(FacesContext facesContext, UIComponent component,
			String value) {
		if (value == null || value.equals(""))
			return null;

		try {
			String id = value;

			Collection items = (Collection) component.getAttributes().get(
					"itens");

			Long valueOf = getValorDoId(id);

			return findById(items, valueOf);

		} catch (Exception ex) {
			throw new ConverterException("Não foi possível converter", ex);
		}
	}

	private Long getValorDoId(String id) {
		try {
			Long valueOf = Long.valueOf(id);

			return valueOf;
		} catch (Exception ex) {
			// Necessário pois a combo poderá conter um valor inválido para
			// gravar.
			return -1L;
		}
	}

	private Object findById(Collection collection, Long idToFind) {
		try {
			for (Object itemLista : collection) {
				Long id = ((Model) itemLista).getId();

				if (id.equals(idToFind)) {

					return itemLista;
				}
			}
		} catch (Exception ex) {
			return null;
		}

		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext
	 * , javax.faces.component.UIComponent, java.lang.Object)
	 */
	@Override
	public String getAsString(FacesContext facesContext, UIComponent component,
			Object value) {
		if (value == null) {
			return null;
		}

		if (!(value instanceof Model)) {
			return null;
		}

		Long idBasico = ((Model) value).getId();

		if (idBasico != null) {
			return idBasico.toString();
		}

		return null;
	}
}
